package com.shuorikeji.huohuo.ui;

import android.content.Intent;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.shuorikeji.huohuo.R;
import com.shuorikeji.huohuo.base.BasePresenterActivity;
import com.shuorikeji.huohuo.common.Constant;
import com.shuorikeji.huohuo.mvp.AllPresenter;
import com.shuorikeji.huohuo.utils.BusinessUtils;

import butterknife.BindView;

public class WebViewActivity extends BasePresenterActivity<AllPresenter> {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.wv_content)
    WebView wvContent;

    private String title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getmImmersionBar().reset().statusBarColor(R.color.transparent).statusBarDarkFont(true, 0.2f).init();
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_web_view);
    }

    @Override
    protected void initData() {
        initWebSet();
        initIntent();
        ivBack.setOnClickListener(view -> {
            finish();
        });
    }

    private void initWebSet() {
        wvContent.clearCache(true);
        WebSettings settings = wvContent.getSettings();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        settings.setTextZoom(80);
        settings.setJavaScriptEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setDomStorageEnabled(true);
        settings.setDisplayZoomControls(false); // 设置显示缩放按钮(minsdk=11)
        settings.setBuiltInZoomControls(true);   //设置支持缩放
        settings.setAppCacheEnabled(false);
        settings.setSupportZoom(true);

        wvContent.setOverScrollMode(View.OVER_SCROLL_NEVER);//webview滚动拖动到顶部或底部阴影
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(wvContent, true);        //跨域cookie读取
        }
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setBlockNetworkImage(false);
        settings.setAllowFileAccess(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            settings.setAllowFileAccessFromFileURLs(true);
            settings.setAllowUniversalAccessFromFileURLs(true);
        }
        wvContent.setWebChromeClient(new MyWebChromeClient());//设置可alert弹窗
        wvContent.setWebViewClient(new MyWebViewClient());
    }

    private void initIntent() {
        Intent intent = getIntent();
        title = intent.getStringExtra("title");
        tvTitle.setText(title);
        if ("用户协议".equals(title)) {
            wvContent.loadUrl(Constant.USER_XY);
        } else if ("隐私协议".equals(title)) {
            wvContent.loadUrl(Constant.YS_RULE);
        }
    }

    public static class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (newProgress == 100) {

            }
        }
    }

    public static class MyWebViewClient extends WebViewClient {
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }


        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            //移除H5页面中的标题
            if (url.endsWith("zlH5R") || url.endsWith("zlH5W") || url.contains("zlH5") || url.contains("rightDesc")) {
                //编写 javaScript方法
                String javascript = "javascript:function hideOther() {" +
                        "var headers = document.getElementsByTagName('header');" +
                        "var lastHeader = headers[headers.length-1];" +
                        "lastHeader.remove();" +
                        "}";
                //创建方法
                view.loadUrl(javascript);
                //加载方法
                view.loadUrl("javascript:hideOther();");
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BusinessUtils.clearWebView(wvContent);
    }
}